package model;

import client.Settings;

/**
 * @author Danilov
 *
 */
public class CommandProcessor {
	private final Model data;

	public CommandProcessor(Model data){
		this.data = data;
	}

	/**
	 * Accepts user input and makes respective actions
	 * @param cmd - user input command
	 * @return Result string, if command is recognized it returns confirmation string, and Erroneous otherwise 
	 */
	public String postInput(String cmd){
		String result = "Wrong input. Try again. Type in help to see available commands or simply input: \r\n  post %positiveNumber%";

		if (cmd.matches("help")) {
			return String.format("PrimeTerminal can request a server to decompose an entered number to the product of primes. %n Available commands are:%n help%n post %%positivenumber%%%n ip %%ipaddress:port%%%n exit");
		}

		if (cmd.matches("exit")) {
			System.exit(0);
		} 

		if (cmd.startsWith("post")){
			// select very primitive numbers
			if (cmd.matches("post [012357]")){
				result = "Entered number is very simple, please try another one";
			} else if (cmd.matches("post \\d+")) {

				// Cut the input to the only value
				String value = cmd.substring(5);
				
				result = String.format("Number %s have been sent to the Server", value);

				// Add new request to it
				data.addRequest(new ServerRequest("toPrimes:" + value) {
					
					/**
					 * Processes replies, update user interfaces and all interested parties about its being change.
					 */
					@Override public void processReply(String r) {
						data.setChanged();
						data.notifyObservers(r);
					}
				});

			}
			return result;
		} 

		if (cmd.matches("ip \\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b:\\d+")){
			String host = cmd.substring(3, cmd.indexOf(':'));
			Settings ss = Settings.getInstance();
			ss.setHost(host);
			int port = 0;
			try {
			port = new Integer(cmd.substring(cmd.indexOf(':') + 1));
			ss.setPort(port);
			} catch (NumberFormatException ex){
				ex.printStackTrace();
			}
			ss.save();
			result = String.format("Server ip address changed to %s:%d", host, port);
		}
		return result;
	}
}
